package com.atguigu.exam.service.impl;

import com.atguigu.exam.properties.MinioProperties;
import com.atguigu.exam.service.FileUploadService;
import io.minio.*;
import io.minio.errors.MinioException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.Date;
import java.util.UUID;

/**
 * projectName: com.atguigu.exam.service.impl
 *
 * @author: 赵伟风
 * description:
 */
@Service
@Slf4j
@EnableConfigurationProperties(MinioProperties.class)
public class FileUploadServiceImpl implements FileUploadService {
    @Autowired
    private MinioProperties minioProperties;

    @Override
    public String uploadFile(MultipartFile file) {
        try {
            // 1.创建客户端对象
            MinioClient minioClient = MinioClient.builder()
                    //设置Minio服务器的地址
                    .endpoint(minioProperties.getEndpoint())
                    //设置用户名和密码
                    .credentials(minioProperties.getAccessKey(), minioProperties.getSecretKey())
                    .build();

            // 检查存储桶是否已经存在
            boolean isExist =
                    minioClient.bucketExists(BucketExistsArgs.builder().bucket(minioProperties.getBucketName()).build());
            if (isExist) {
                System.out.println("Bucket" + minioProperties.getBucketName() + "already exists.");
            } else {
                //如果桶不存在则创建它
                minioClient.makeBucket(MakeBucketArgs.builder().bucket(minioProperties.getBucketName()).build());
            }
            String originalFilename = file.getOriginalFilename();
            InputStream inputStream = file.getInputStream();
            long size = file.getSize();
            String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
            String prefix = UUID.randomUUID().toString().replaceAll("-", "");
            String formatDate = DateFormatUtils.format(new Date(), "yyyy/MM/dd");
            String fileName = formatDate + "/" + prefix + suffix;

            //当传入输入流的时候使用PutObjectArgs
            PutObjectArgs putObjectArgs = PutObjectArgs.builder()
                    .bucket(minioProperties.getBucketName())
                    .object(fileName)
                    .stream(inputStream, size, -1)
                    .build();

            //使用putObject上传文件到Minio服务器的桶中
            minioClient.putObject(putObjectArgs);
            return minioProperties.getEndpoint() + "/" + minioProperties.getBucketName() + "/" + fileName;
        } catch (Exception e) {
            System.out.println("Error occurred: " + e);
        }
        return "";
    }
}
